package com.cloud.qualitycontrol.controller;

import com.cloud.qualitycontrol.dao.FileFolderRepository;
import com.cloud.qualitycontrol.model.FileFolder;
import com.cloud.qualitycontrol.model.QualityNode;
import com.cloud.qualitycontrol.service.QualityTreeService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

import static com.cloud.qualitycontrol.util.CommonVar.*;

/**
 * 处理质量管理树操作请求
 */
@RestController
public class QualityTreeController {

    @Autowired
    private QualityTreeService qualityTreeService;
    @Autowired
    private FileFolderRepository fileFolderRepository;

    @ApiOperation(value = "初始化树")
    @PostMapping("/quality/node/init")
    public String init() {
        return qualityTreeService.initTree();
    }

    @ApiOperation(value = "增加一个节点")
    @PostMapping("/quality/node/add")
    public QualityNode add(@RequestBody QualityNode qNode) {
        if (StringUtils.isBlank(qNode.getName())) {
            throw new IllegalArgumentException("节点名不能为空");
        }
        qualityTreeService.addNode(qNode);
        return qNode;
    }

    @ApiOperation(value = "删除一个节点")
    @DeleteMapping(value = "/quality/node/{id}")
    public String deleteNodeById(@PathVariable("id") String id) {
        qualityTreeService.deleteById(id);
        return OPERATE_SUCCESS_STR;
    }

    @ApiOperation(value = "根据ID查询节点")
    @GetMapping("/quality/node/{id}")
    public QualityNode getNodeById(@PathVariable String id){
        return qualityTreeService.selectById(id);
    }

    @ApiOperation(value = "根据 qualityId 查询FileFolder")
    @GetMapping("/quality/node/folder/{qualityId}")
    public Set<FileFolder> getFileFolderByQualityId(@PathVariable String qualityId){
        return fileFolderRepository.getByQualityId(qualityId);
    }

    @ApiOperation(value = "根据Parent ID查询节点")
    @GetMapping("/quality/node/parent/{parentId}")
    public Set<QualityNode> getNodeByParentId(@PathVariable String parentId){
        return qualityTreeService.selectByParentId(parentId);
    }

    @ApiOperation(value = "更新节点")
    @PostMapping("/quality/node/update")
    public QualityNode updateNode(@RequestBody QualityNode qNode){
        if (qNode.getId() == null){
            throw new IllegalArgumentException("Node id is null");
        }
        return qualityTreeService.updateNode(qNode);
    }

    @ApiOperation(value = "获取整颗树")
    @GetMapping("/tree")
    public String getQualityNodeTree() {
        try {
            return qualityTreeService.selectAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return OPERATE_FAILED_STR;
    }

}
